<template>
  <base-content>
  <div class="q-pa-md">
    <q-form @submit="getStuAttendStat" class="flex q-gutter-md">
      <q-select
        name="preferred_genre"
        v-model="semesterPreferred"
        :options="semesterOption"
        :option-label="(item) => item === null ? null : item.semesterYear + ' ' + item.semesterType"
        :option-value="(item) => item === null ? null : item.semesterId"
        color="primary"
        filled
        clearable
        label="请选择学期"
        style="width: 300px;"
      />
      <q-btn icon="search" label="查询考勤数据" type="submit" color="primary"/>
    </q-form>
    <q-table
      :title="this.semesterPreferred.semesterYear+this.semesterPreferred.semesterType+' 学业预警数据'"
      style="margin-top: 20px"
      :data="studentScoreTable.data"
      :columns="studentScoreTable.columns"
      :filter="studentScoreTable.filter"
      row-key="name"
      no-data-label="没有找到任何信息"
    >
      <template v-slot:top-right>
        <q-input dense debounce="300" v-model="studentScoreTable.filter" placeholder="Search">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
        <q-btn
          color="primary"
          icon-right="archive"
          label="导出数据"
          no-caps
          @click="exportTable"
          style="margin-left: 20px"
        />
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">

          <q-td :props="props" key="studentNumber">{{props.row.studentNumber}}</q-td>
          <q-td :props="props" key="studentRealName">{{props.row.studentRealName}}</q-td>
          <q-td :props="props" key="studentSex">{{props.row.studentSex}} </q-td>
          <q-td :props="props" key="gradeId">{{props.row.gradeId}} </q-td>
          <q-td :props="props" key="collegeName">{{props.row.collegeName}} </q-td>
          <q-td :props="props" key="majorName">{{props.row.majorName}} </q-td>
          <q-td :props="props" key="className">{{props.row.className}} </q-td>
          <q-td :props="props" key="semesterYear">{{props.row.semesterYear}}</q-td>
          <q-td :props="props" key="semesterType">{{props.row.semesterType}}</q-td>
          <q-td :props="props" key="bxFail">{{props.row.bxFail}} </q-td>
          <q-td :props="props" key="xxFail">{{props.row.xxFail}} </q-td>
          <q-td :props="props" key="rank">{{props.row.rank}}</q-td>
          <q-td :props="props" key="operating">
            <q-btn label="查看详情" @click="detail(props.row.studentNumber)"/>
            <q-btn label="学生邮件" @click="confirmToStu(props.row.studentNumber,props.row.studentRealName,props.row.rank)" buttons label-ok="更改" label-cancel="取消"/>
            <q-btn label="家长邮件" @click="confirmToParent(props.row.studentNumber,props.row.studentRealName,props.row.rank)"/>
          </q-td>
        </q-tr>
      </template>
    </q-table>
  </div>
  </base-content>
</template>

<script>
import { exportFile } from 'quasar'
import BaseContent from '../../components/BaseContent/BaseContent'

function wrapCsvValue (val, formatFn) {
  // eslint-disable-next-line no-void
  let formatted = formatFn !== void 0 ? formatFn(val) : val
  // eslint-disable-next-line no-void
  formatted = formatted === void 0 || formatted === null ? '' : String(formatted)

  formatted = formatted.split('"').join('""')
  /**
     * Excel accepts \n and \r in strings, but some other CSV parsers do not
     * Uncomment the next two lines to escape new lines
     */
  // .split('\n').join('\\n')
  // .split('\r').join('\\r')

  return `"${formatted}"`
}

export default {
  name: 'AdminScore',
  components: { BaseContent },
  data () {
    return {
      currentUserInfo: JSON.parse(sessionStorage.getItem('user_object')),
      semesterPreferred: { semesterId: '', semesterType: '', semesterYear: '' }, // 设置默认值为空
      semesterOption: [], // 这里是数据库返回的数据，数组里的对象用item标识
      studentScoreTable: {
        filter: '',
        columns: [
          { name: 'studentNumber', label: '学号', align: 'left', field: 'studentNumber', sortable: true },
          { name: 'studentRealName', label: '姓名', align: 'left', field: 'studentRealName' },
          { name: 'studentSex', label: '性别', align: 'left', field: 'studentSex' },
          { name: 'gradeId', label: '年级', align: 'left', field: 'gradeId' },
          { name: 'collegeName', label: '学院', align: 'left', field: 'collegeName', sortable: true },
          { name: 'majorName', label: '专业', align: 'left', field: 'majorName', sortable: true },
          { name: 'className', label: '班级', align: 'left', field: 'className', sortable: true },
          { name: 'semesterYear', label: '学年', align: 'left', field: 'semesterYear', sortable: true },
          { name: 'semesterType', label: '学期', align: 'left', field: 'semesterType', sortable: true },
          { name: 'bxFail', label: '必修课挂科数', align: 'left', field: 'bxFail', sortable: true },
          { name: 'xxFail', label: '选修课挂科数', align: 'left', field: 'xxFail', sortable: true },
          { name: 'rank', label: '预警等级', align: 'left', field: 'rank', sortable: true },
          { name: 'operating', label: '操作', align: 'center', field: 'operating' }
        ],
        data: []
      }
    }
  },
  created () {
    this.getAllSemesterYear()
  },
  methods: {
    confirmToStu (e1, e2, e3) {
      const _e1 = e1
      const _e3 = e3
      this.$q.dialog({
        title: '邮件发送',
        message: '确认给' + e1 + ' ' + e2 + ' 发送成绩预警邮件吗?',
        cancel: '取消',
        persistent: true,
        ok: '确认发送'
      }).onOk(() => {
        const query = {
          url: '/MailSenderScoreServlet',
          methods: 'post',
          type: 'FORM',
          data: {
            userid: _e1,
            userType: 'student',
            attend: _e3
          }
        }
        this.$fetchData(query).then(res => {
          if (res.data.indexOf('未注册')) {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          } else {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          }
        }).catch(e => {
          console.log(e)
        })
      }).onCancel(() => {
        // console.log('>>>> Cancel')
      }).onDismiss(() => {
        // console.log('I am triggered on both OK and Cancel')
      })
    },
    confirmToParent (e1, e2, e3) {
      const _e1 = e1
      const _e3 = e3
      this.$q.dialog({
        title: '邮件发送',
        message: '确认给' + e1 + ' ' + e2 + ' 的家长发送成绩预警邮件吗?',
        cancel: '取消',
        persistent: true,
        ok: '确认发送'
      }).onOk(() => {
        const query = {
          url: '/MailSenderScoreServlet',
          methods: 'post',
          type: 'FORM',
          data: {
            userid: _e1,
            userType: 'parent',
            attend: _e3
          }
        }
        this.$fetchData(query).then(res => {
          if (res.data.indexOf('未注册')) {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          } else {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          }
        }).catch(e => {
          console.log(e)
        })
      }).onCancel(() => {
        // console.log('>>>> Cancel')
      }).onDismiss(() => {
        // console.log('I am triggered on both OK and Cancel')
      })
    },
    // 查看学生挂科详情
    detail (e) {
      this.$router.push({
        path: '/AdminFailExams',
        query: {
          stuN: e
        }
      })
    },
    exportTable () {
      // naive encoding to csv format
      const content = [this.studentScoreTable.columns.map(col => wrapCsvValue(col.label))].concat(
        this.studentScoreTable.data.map(row => this.studentScoreTable.columns.map(col => wrapCsvValue(
          typeof col.field === 'function'
            ? col.field(row)
            // eslint-disable-next-line no-void
            : row[col.field === void 0 ? col.name : col.field],
          col.format
        )).join(','))
      ).join('\r\n')

      const status = exportFile(
        this.semesterPreferred.semesterYear + this.semesterPreferred.semesterType + '成绩数据.csv',
        '\uFEFF' + content,
        'text/csv'
      )

      if (status !== true) {
        this.$q.notify({
          message: '导出文件失败...',
          color: 'negative',
          icon: 'warning'
        })
      }
    },
    // 获取学期显示在下拉框
    getAllSemesterYear () {
      const queryYear = {
        url: '/getAllSemesterServlet',
        methods: 'get'
      }
      this.$fetchData(queryYear).then(res => {
        if (res.data !== null) {
          console.log(res)
          this.semesterPreferred = res.data[res.data.length - 1]// 绑定的默认数据为最新的学期
          this.semesterOption = res.data// 将获取到的学期数据返回下拉框的选择里
        } else {
          this.$q.notify({
            icon: 'announcement',
            message: '获取记录为空',
            color: 'red',
            position: 'top',
            timeout: 1500
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 查询学生成绩数据
    getStuAttendStat () {
      const queryYear = {
        url: '/AdminScoreServlet',
        methods: 'get',
        params: {
          year: this.semesterPreferred.semesterYear,
          type: this.semesterPreferred.semesterType
        }
      }
      this.$fetchData(queryYear).then(res => {
        console.log(res)
        this.studentScoreTable.data = res.data// 将查询结果放在表格数据，执行完该查询之后再进行学业预警等级的判断
      }).catch(e => {
        console.log(e)
      })
    }
  }
}
</script>

<style scoped>

</style>
